import { Context } from 'koa';
import KoaRouter from 'koa-router';
import { v4 as uuidv4 } from 'uuid';
import { validate } from '@/middleware/validate';
import Joi from 'joi';
import { CheckList } from '@/models/checkList';
import { Check } from '@/models/check';
import { CreateCheckListRequest } from '@/types/route';

export default (router: KoaRouter) => {
    // 新增 CheckList
    router.post('/card/:cardId/checklist', 
        validate(Joi.object({
            title: Joi.string().required().min(1).max(50).messages({
                'string.empty': '标题不能为空',
                'string.min': '标题不能为空',
                'string.max': '标题长度不能超过50个字符',
                'any.required': '标题是必填项'
            })
        })), 
        async (ctx: Context) => {
            try {
                const { cardId } = ctx.params;
                const { title } = ctx.request.body as CreateCheckListRequest;

                // 创建新的 CheckList
                const newCheckList = await CheckList.create({
                    checkListId: uuidv4(), // 使用 UUID 生成唯一 ID
                    cardId,
                    title,
                    createdAt: Date.now(),
                    updatedAt: Date.now()
                });

                ctx.setResponse(newCheckList, '创建成功');
            } catch {
                ctx.status = 500;
                ctx.setResponse(null, '创建失败', 500);
            }
        }
    );

    // 修改 CheckList 标题
    router.put('/checklist/:checkListId', 
        validate(Joi.object({
            title: Joi.string().required().min(1).max(50).messages({
                'string.empty': '标题不能为空',
                'string.min': '标题不能为空',
                'string.max': '标题长度不能超过50个字符',
                'any.required': '标题是必填项'
            })
        })), 
        async (ctx: Context) => {
            try {
                const { checkListId } = ctx.params;
                const { title } = ctx.request.body as { title: string };

                const updatedCheckList = await CheckList.findOneAndUpdate(
                    { checkListId },
                    { 
                        title,
                        updatedAt: Date.now()
                    },
                    { 
                        new: true,
                        projection: { _id: 0, __v: 0 }
                    }
                );

                if (!updatedCheckList) {
                    ctx.status = 404;
                    return ctx.setResponse(null, 'CheckList不存在', 404);
                }

                ctx.setResponse(updatedCheckList, '更新成功');
            } catch {
                ctx.status = 500;
                ctx.setResponse(null, '更新失败', 500);
            }
        }
    );

    // 删除 CheckList 及其下属 Checks
    router.delete('/checklist/:checkListId', async (ctx: Context) => {
        const session = await CheckList.startSession();
        session.startTransaction();
        const { checkListId } = ctx.params;
        try {
            // 查找 CheckList 是否存在
            const checkList = await CheckList.findOne({ checkListId }).session(session);
            if (!checkList) {
                await session.abortTransaction();
                ctx.status = 404;
                return ctx.setResponse(null, 'CheckList不存在', 404);
            }

            // 删除 CheckList
            await CheckList.deleteOne({ checkListId }).session(session);

            // 删除该 CheckList 下的所有 Checks
            await Check.deleteMany({ checkListId }).session(session);

            await session.commitTransaction();
            ctx.setResponse(null, '删除成功');
        } catch {
            await session.abortTransaction();
            ctx.status = 500;
            ctx.setResponse(null, '删除失败', 500);
        } finally {
            session.endSession();
        }
    });
};
